package com.czl.module_service.viewmodel.assetUse

import android.util.Log
import androidx.databinding.ObservableField
import com.blankj.utilcode.util.GsonUtils
import com.czl.base.base.BaseBean
import com.czl.base.base.BaseViewModel
import com.czl.base.base.MyApplication
import com.czl.base.binding.command.BindingAction
import com.czl.base.binding.command.BindingCommand
import com.czl.base.data.DataRepository
import com.czl.base.data.bean.tengyun.AddApplySortBean
import com.czl.base.data.bean.tengyun.SortBean
import com.czl.base.data.bean.tengyun.StorehouseBean
import com.czl.base.event.LiveBusCenter
import com.czl.base.event.SingleLiveEvent
import com.czl.base.extension.ApiSubscriberHelper
import com.czl.base.util.DateHelper
import com.czl.base.util.RxThreadHelper
import com.czl.module_service.adapter.asset.AssetStoreAllocationApplyAddAdapter

class AssetStoreAllocationApplyAddViewModel(application: MyApplication, model: DataRepository) :
    BaseViewModel<DataRepository>(application, model) {

    var currentPage = 1
    val uc = UiChangeEvent()
    var sortBean : SortBean? = null
    var storehouseOutId : Int? = null
    var storehouseInId : Int? = null
    var applyComment = ObservableField("")
    var list : MutableList<SortBean> = arrayListOf()
    var adapter : AssetStoreAllocationApplyAddAdapter? = null

    class UiChangeEvent {
        val loadCompleteEvent: SingleLiveEvent<MutableList<SortBean>> = SingleLiveEvent()
        val storeCompleteEvent: SingleLiveEvent<List<StorehouseBean.StoreHouseListBean>> = SingleLiveEvent()
        val onOutStoreEvent: SingleLiveEvent<Void> = SingleLiveEvent()
        val onInStoreEvent: SingleLiveEvent<Void> = SingleLiveEvent()
        val addCompleteEvent: SingleLiveEvent<BaseBean<Any?>> = SingleLiveEvent()
    }

    val onOutStoreCommand: BindingCommand<Any> = BindingCommand(BindingAction {
        uc.onOutStoreEvent.call()
    })

    val onInStoreCommand: BindingCommand<Any> = BindingCommand(BindingAction {
        uc.onInStoreEvent.call()
    })

    val addSortLayout: BindingCommand<Any> = BindingCommand(BindingAction {
        getSortList()
    })

    val addUsageSort : BindingCommand<Any> = BindingCommand(BindingAction {
        addUseApplication()
    })

    fun getSortList() {
        val list : MutableList<SortBean> = arrayListOf()
        list.add(SortBean())
        uc.loadCompleteEvent.postValue(list)
    }

    fun getStorehouseByUserId() {
        model.mTengYunHttpDataSource.getStorehouseByUserId(
            GsonUtils.toJson(
                mapOf(
                    "userId" to model.getLocalUserInfo()?.userId,
                    "companyId" to model.getLoginCompanyId()?.toInt()
                )
            )
        )
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .subscribe(object : ApiSubscriberHelper<BaseBean<StorehouseBean>>() {
                override fun onResult(t: BaseBean<StorehouseBean>) {
                    if (t.state == 0) {
                        if(t.data?.list?.size!! > 0) {
                            uc.storeCompleteEvent.postValue(t.data?.list)
                        } else {
                            showNormalToast("无可调拨仓库")
                        }
                    } else {
                        showErrorToast(t.msg)
                    }
                    dismissLoading()
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }
            })
    }

    /*fun getManageCompanystorehouseList() {
        model.mTengYunHttpDataSource.getManageCompanystorehouseList(
            GsonUtils.toJson(
                mapOf(
                    "companyId" to model.getLoginCompanyId()?.toInt()
                )
            )
        )
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .subscribe(object : ApiSubscriberHelper<BaseBean<ListBean<StoreHouseListBean>>>() {
                override fun onResult(t: BaseBean<ListBean<StoreHouseListBean>>) {
                    if (t.errorCode == 0) {
                        uc.storeCompleteEvent.postValue(t.data?.list)
                    } else {
                        showErrorToast(t.msg)
                    }
                    dismissLoading()
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }
            })
    }*/

    // 新增领用申请
    private fun addUseApplication() {
        val data = adapter?.data
        if(data != null) {
            list = data
        }
        Log.e("viewModel", "data:" +data?.size)
        val filterList = list.filter { it. sortId != null }
        if (applyComment.get().isNullOrEmpty()) {
            showNormalToast("请填写调拨原因")
            return
        }
        if (storehouseInId == null) {
            showNormalToast("请选择调入仓库")
            return
        }
        if (storehouseOutId == null) {
            showNormalToast("请选择调出仓库")
            return
        }
        if (filterList.isEmpty()) {
            showNormalToast("请选择物品")
            return
        }
        val filterList2 = filterList.filter { it.sortNum == 0 }
        if (filterList2.isNotEmpty()) {
            showNormalToast("物品数量不能为0")
            return
        }
        val list : MutableList<AddApplySortBean> = arrayListOf()
        filterList.forEach {
            it.count = it.sortNum!!
            it.applyNum = it.sortNum
            it.lendNum = it.sortNum
        }
        model.mTengYunHttpDataSource.addApplyInfo(
            GsonUtils.toJson(
                mapOf(
                    "applyPersonId" to model.getLocalUserInfo()?.userId,
                    "applyPersonName" to model.getLocalUserInfo()?.userName,
                    "outCompanyId" to model.getLoginCompanyId()?.toInt(),
                    "applyCompanyId" to model.getLoginCompanyId()?.toInt(),
                    "applyCompanyName" to model.getLocalUserInfo()?.companyName,
                    "applyCompanyShortName" to model.getLocalUserInfo()?.companyName,
                    "applyDate" to DateHelper.getNow(),
                    "applyComment" to applyComment.get(),
                    "workId" to "1",
                    "applyList" to filterList,
                    "storehouseOutId" to storehouseOutId,
                    "storehouseInId" to storehouseInId,
                    "applyType" to 5
                )
            )
        )
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .doOnSubscribe { showLoading() }
            .subscribe(object : ApiSubscriberHelper<BaseBean<Any?>>() {
                override fun onResult(t: BaseBean<Any?>) {
                    if (t.state == 0) {
                        showNormalToast("新增成功")
                        uc.addCompleteEvent.postValue(BaseBean<Any?>())
                        LiveBusCenter.postGoToTabEvent(1)
                    } else {
                        showErrorToast(t.msg)
                    }
                    dismissLoading()
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }
            })
    }

}